package com.sxt.test;

import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.sxt.entity.ELitter;
import com.sxt.entity.EMail;
import com.sxt.entity.EUser;
import com.sxt.factory.HibernateSessionFactory;

public class Demo1 {
	/**
	 * 通过用户查找信息
	 */
	@Test
	public void test1() {
		Session session = HibernateSessionFactory.getSession();
		EUser u1 = (EUser) session.get(EUser.class, 1);
		System.out.println(u1.getName());
		Set<EMail> ms1 = u1.geteMails();
		for (EMail m1 : ms1) {
			System.out.println("--->" + m1.getAddr());
			Set<ELitter> ls1 = m1.geteLitters();
			for (ELitter l1 : ls1) {
				System.out.println("------>" + l1.getTitle());
			}
		}
		session.close();
	}
	
	/**
	 * 通过信件查找信息
	 */
	@Test
	public void test2() {
		Session session = HibernateSessionFactory.getSession();
		ELitter litter = (ELitter) session.get(ELitter.class, 3);
		System.out.println(litter.getTitle());
		EMail mail = (EMail) session.get(EMail.class, litter.getEmail().getId());
		System.out.println("-->" + mail.getAddr());
		EUser user = (EUser) session.get(EUser.class, mail.getUser().getId());
		System.out.println("----->" + user.getName());
		session.close();
	}
	
	/**
	 * 通过Litter添加所有信息
	 */
	@Test
	public void test3() {
		Session session = HibernateSessionFactory.getSession();
		
		EUser user = new EUser("陈凯");
		EMail mail = new EMail(null, "chenkai@qq.com", user);
		ELitter litter = new ELitter(null, "陈凯测试", mail);

		Transaction tx = session.beginTransaction();
		session.save(litter);
		tx.commit();
		session.close();
	}
	
	/**
	 * 通过User添加所有信息
	 */
	@Test
	public void test4() {
		Session session = HibernateSessionFactory.getSession();
		
		ELitter litter = new ELitter(null, "张七招测试", null);
		EMail mail = new EMail(null, "zhangqizhao@qq.com", null);
		EUser user = new EUser("张七招");
		
		user.geteMails().add(mail);
		mail.geteLitters().add(litter);
		
		litter.setEmail(mail);
		mail.setUser(user);
		
		Transaction tx = session.beginTransaction();
		session.save(user);
		tx.commit();
		session.close();
	}
	
	/**
	 * 把张三的所有邮箱改成李四的
	 */
	@Test
	public void test5() {
		Session session = HibernateSessionFactory.getSession();
		
		EUser zhangsan = (EUser) session.get(EUser.class, 1);
		EUser lisi = (EUser) session.get(EUser.class, 2);
		Set<EMail> zmails = zhangsan.geteMails();
		for (EMail mail : zmails) {
			mail.setUser(lisi);
		}
		
		Transaction tx = session.beginTransaction();
		session.update(zhangsan);
		tx.commit();
		session.close();
		
	}

	/**
	 * 删除王五，级联删除邮箱和邮件
	 */
	@Test
	public void test6() {
		Session session = HibernateSessionFactory.getSession();
		EUser wangwu = (EUser) session.get(EUser.class, 3);
		Transaction tx = session.beginTransaction();
		session.delete(wangwu);
		tx.commit();
		session.close();
	}
}
